<template>
  <div class="admin-container">
    <h2>访客审批</h2>

    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6" v-for="stat in stats" :key="stat.label">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-value" :class="stat.class">{{ stat.value }}</div>
          <div class="stat-label">{{ stat.label }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 访客列表 -->
    <el-card class="visitor-list">
      <template #header>
        <div class="card-header">
          <div class="left">
            <span class="title">访客申请列表</span>
          </div>
          <div class="right">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索访客姓名/手机号"
              class="search-input"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table :data="filteredVisitorList" border v-loading="loading">
        <el-table-column prop="name" label="访客姓名" width="120" />
        <el-table-column prop="phoneNumber" label="联系电话" width="120" />
        <el-table-column prop="purpose" label="到访事由" width="180" />
        <el-table-column prop="arrivalTime" label="到访时间" width="160">
          <template #default="{ row }">
            {{ row.arrivalTime || '未设置' }}
          </template>
        </el-table-column>
        <el-table-column prop="departureTime" label="预计离开" width="160">
          <template #default="{ row }">
            {{ row.departureTime || '未设置' }}
          </template>
        </el-table-column>
        <el-table-column prop="approvalStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.approvalStatus)">
              {{ getStatusText(row.approvalStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button-group>
              <el-button 
                type="success" 
                link 
                :disabled="row.approvalStatus !== 'PENDING'"
                @click="handleApprove(row)"
              >
                通过
              </el-button>
              <el-button 
                type="danger" 
                link 
                :disabled="row.approvalStatus !== 'PENDING'"
                @click="handleReject(row)"
              >
                拒绝
              </el-button>
              <el-button 
                type="danger" 
                link 
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getAllVisitors, approveVisitor, deleteVisitor } from '@/api/adminApi'

// 数据状态
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const visitorList = ref([])

// 统计数据
const stats = ref([
  { label: '待审核', value: 0, class: 'warning' },
  { label: '今日通过', value: 0, class: 'success' },
  { label: '今日拒绝', value: 0, class: 'danger' },
  { label: '累计访客', value: 0, class: 'info' }
])

// 计算属性：过滤后的列表
const filteredVisitorList = computed(() => {
  if (!searchKeyword.value) return visitorList.value
  const keyword = searchKeyword.value.toLowerCase()
  return visitorList.value.filter(visitor =>
    visitor.name.toLowerCase().includes(keyword) ||
    visitor.phoneNumber.includes(keyword)
  )
})

// 获取状态文本
const getStatusText = (status) => {
  const statuses = {
    'PENDING': '待审核',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝'
  }
  return statuses[status] || status
}

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger'
  }
  return types[status] || 'info'
}

// 获取访客列表
const fetchVisitorList = async () => {
  loading.value = true
  try {
    const response = await getAllVisitors()
    if (response.code === 200) {
      visitorList.value = response.data.visitors
      total.value = response.data.total || visitorList.value.length
      updateStats()
    }
  } catch (error) {
    ElMessage.error('获取访客列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 更新统计数据
const updateStats = () => {
  const today = new Date().toISOString().split('T')[0]
  
  stats.value[0].value = visitorList.value.filter(v => v.approvalStatus === 'PENDING').length
  stats.value[1].value = visitorList.value.filter(v => 
    v.approvalStatus === 'APPROVED' && 
    v.updatedAt.startsWith(today)
  ).length
  stats.value[2].value = visitorList.value.filter(v => 
    v.approvalStatus === 'REJECTED' && 
    v.updatedAt.startsWith(today)
  ).length
  stats.value[3].value = visitorList.value.length
}

// 处理审批通过
const handleApprove = async (visitor) => {
  try {
    await ElMessageBox.confirm('确定通过该访客申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    })
    
    const response = await approveVisitor({
      visitorId: visitor.visitorId,
      status: 'APPROVED'
    })
    
    if (response.code === 200) {
      ElMessage.success('已通过访客申请')
      fetchVisitorList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
      console.error(error)
    }
  }
}

// 处理审批拒绝
const handleReject = async (visitor) => {
  try {
    await ElMessageBox.confirm('确定拒绝该访客申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await approveVisitor({
      visitorId: visitor.visitorId,
      status: 'REJECTED'
    })
    
    if (response.code === 200) {
      ElMessage.success('已拒绝访客申请')
      fetchVisitorList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
      console.error(error)
    }
  }
}

// 处理删除
const handleDelete = async (visitor) => {
  try {
    await ElMessageBox.confirm('确定删除该访客记录吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteVisitor(visitor.visitorId)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchVisitorList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 初始化
onMounted(() => {
  fetchVisitorList()
})
</script>

<style scoped>
.admin-container {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-value.warning { color: #E6A23C; }
.stat-value.success { color: #67C23A; }
.stat-value.danger { color: #F56C6C; }
.stat-value.info { color: #909399; }

.stat-label {
  color: #606266;
  font-size: 14px;
}

.visitor-list {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>